package com.zwj.hmall.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 事务失效场景
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/8/8 10:25
 */
@Slf4j
@Service
public class UserService2 {
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private UserService userService;

    public void update() {
        this.updateUser();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void updateUser() {
        jdbcTemplate.update("update tb_user set money = money + ? where account = ?", 1000, "jack");
        jdbcTemplate.update("update tb_user set money = money + ? where account = ?", 1000, "mike");
        throw new RuntimeException();
    }

    @Transactional(rollbackFor = Exception.class)
    public void update3() throws Exception {
        jdbcTemplate.update("update tb_user set money = money + ? where account = ?", 1000, "jack");
        jdbcTemplate.update("update tb_user set money = money + ? where account = ?", 1000, "mike");
        throw new Exception();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void update4() {
        jdbcTemplate.update("update tb_user set money = money + ? where account = ?", 1000, "jack");
        userService.update6();
    }
}
